<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" @submit.prevent>
      <!-- <el-form-item label="区域编码" prop="areaCode">
        <el-input
          v-model="queryParams.areaCode"
          placeholder="请输入区域编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="区域名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="上级区域ID" prop="parentId">-->
<!--        <el-input-->
<!--          v-model="queryParams.parentId"-->
<!--          placeholder="请输入上级区域ID"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="排序" prop="sortOrder">-->
<!--        <el-input-->
<!--          v-model="queryParams.sortOrder"-->
<!--          placeholder="请输入排序"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <!-- <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="修改人" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入修改人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['SysTanksArea:SysTanksArea:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['SysTanksArea:SysTanksArea:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['SysTanksArea:SysTanksArea:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['SysTanksArea:SysTanksArea:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysTanksAreaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="区域编码" align="center" prop="areaCode" />
      <el-table-column label="区域名称" align="center" prop="areaName" />
      <el-table-column label="描述" align="center" prop="description" />
<!--      <el-table-column label="上级区域ID" align="center" prop="parentId" />-->
<!--      <el-table-column label="排序" align="center" prop="sortOrder" />-->
      <!-- <el-table-column label="状态：1-启用，0-禁用" align="center" prop="status" /> -->
      <!-- <el-table-column label="创建人" align="center" prop="createdBy" /> -->
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="修改人" align="center" prop="updatedBy" />
      <el-table-column label="修改时间" align="center" prop="updatedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysTanksArea:SysTanksArea:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysTanksArea:SysTanksArea:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改养殖池区域对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="SysTanksAreaRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入区域编码" />
        </el-form-item>
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="上级区域ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入上级区域ID" />
        </el-form-item> -->
        <!-- <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysTanksArea">
import { listSysTanksArea, getSysTanksArea, delSysTanksArea, addSysTanksArea, updateSysTanksArea,logicDeleteSysTanksArea } from "@/api/SysTanksArea/SysTanksArea"
import { listSysTanks } from '@/api/SysTanks/SysTanks'
const { proxy } = getCurrentInstance()

const SysTanksAreaList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaCode: null,
    areaName: null,
    description: null,
    parentId: null,
    sortOrder: null,
    status: 1,
    createdBy: null,
    updatedBy: null,
  },
  rules: {
    areaCode: [
      { required: true, message: "区域编码不能为空", trigger: "blur" }
    ],
    areaName: [
      { required: true, message: "区域名称不能为空", trigger: "blur" }
    ],
    // parentId: [
    //   { required: true, message: "上级区域ID不能为空", trigger: "blur" },
    //   { pattern: /^-?\d+$/, message: "上级区域ID必须为整数", trigger: "blur" }
    // ],
    // sortOrder: [
    //   { required: true, message: "排序不能为空", trigger: "blur" },
    //   { pattern: /^\d+$/, message: "排序必须为非负整数", trigger: "blur" }
    // ],
    // status: [
    //   { required: true, message: "状态：1-启用，0-禁用不能为空", trigger: "change" }
    // ],
    // createdTime: [
    //   { required: true, message: "创建时间不能为空", trigger: "blur" }
    // ],
    // updatedTime: [
    //   { required: true, message: "修改时间不能为空", trigger: "blur" }
    // ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询养殖桶区域列表 */
function getList() {
  loading.value = true
  const params = { ...queryParams.value, status: 1 }
  listSysTanksArea(params)
    .then(res => {
      SysTanksAreaList.value = res.rows || []  //不再 .filter
      total.value = res.total || 0
    })
    .finally(() => (loading.value = false))
}



// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    areaCode: null,
    areaName: null,
    description: null,
    parentId: null,
    sortOrder: null,
    status: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null
  }
  proxy.resetForm("SysTanksAreaRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.pageNum = 1
  queryParams.value.status = 1
  getList()
}


// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加养殖桶区域"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSysTanksArea(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改养殖池区域"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysTanksAreaRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSysTanksArea(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysTanksArea(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// function handleDelete(row) {
//   const _ids = row.id || ids.value;

//   // 先校验是否正在养殖中使用
//   listSysTanks({ areaId: _ids, isFinished: '1', pageNum: 1, pageSize: 1 }).then(res => {
//     if (res.total > 0) {
//       proxy.$modal.msgWarning('该区域正在被养殖中的桶使用，无法删除');
//       return;
//     }

//     proxy.$modal.confirm('是否确认删除养殖区域编号为"' + _ids + '"的数据项？')
//       .then(() => logicDeleteSysTanksArea(_ids))   // ← 只传 ids 数组
//       .then(() => {
//         proxy.$modal.msgSuccess('删除成功');
//         getList();
//       });
//   });
// }


function handleDelete(row) {
  // 统一拿到 id 数组（单行或批量）
  const idList = row?.id ? [row.id] : ids.value
  if (!idList.length) {
    proxy.$modal.msgWarning('请选择要删除的区域')
    return
  }

  // 建立 id -> areaCode 映射
  const codeMap = {}
  SysTanksAreaList.value.forEach(r => { codeMap[r.id] = r.areaCode })

  // 批量校验：只要任意区域存在正在养殖的桶就禁止
  Promise.all(
    idList.map(id =>
      listSysTanks({ areaId: id, isFinished: '1', pageNum: 1, pageSize: 1 })
        .then(res => ({ id, total: res.total }))
    )
  ).then(checkList => {
    const used = checkList.filter(it => it.total > 0)
    if (used.length) {
      // 用 areaCode 提示
      const codes = used.map(it => codeMap[it.id]).filter(Boolean)
      proxy.$modal.msgWarning(
        `区域编码 ${codes.join(',')} 存在正在养殖的池，无法删除`
      )
      return
    }

    return proxy.$modal
      .confirm(`是否确认删除选中的 ${idList.length} 个区域？`)
      .then(() => logicDeleteSysTanksArea(idList))
      .then(() => {
        proxy.$modal.msgSuccess('删除成功')
        getList()
      })
  }).catch(() => {})
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysTanksArea/SysTanksArea/export', {
    ...queryParams.value
  }, `SysTanksArea_${new Date().getTime()}.xlsx`)
}

getList()
</script>
